package steampunk.art;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import steampunk.geom.Geom;
import steampunk.geom.RectGeom;
import steampunk.io.ImageManager;

public class Sprite extends RectGeom implements Art {

	private SpriteGrid grid;
	private int[] frames;
	private BufferedImage currentFrame;
	private Graphics2D frameGraphics;
	private boolean loop = false;
	private boolean playing = true;
	private double duration = 1.0; // in seconds
	private double ctime = 0.0; // current progress
	
	public Sprite(SpriteGrid grid, int[] frames, double duration, boolean loop) {
		super(grid.getFrameWidth(), grid.getFrameHeight());
		this.grid = grid;
		this.frames = frames;
		this.duration = duration;
		this.loop = loop;
		
		currentFrame = new BufferedImage(
				grid.getFrameWidth(), grid.getFrameHeight(), BufferedImage.TYPE_INT_ARGB);
		frameGraphics = currentFrame.createGraphics();
	}
	
	public Sprite(SpriteGrid grid, int[] frames, double duration) {
		this(grid, frames, duration, true);
	}
	
	public void reset() {
		ctime = 0;
	}
	
	private int getFrameNumber() {
		return frames[(int)((ctime / duration) * frames.length)];
	}
	
	@Override
	public void draw(Graphics2D g) {
		g.drawImage(currentFrame, 0, 0, null);
	}

	@Override
	public void updateArt(double seconds) {
		if (frames.length == 0)
			return;
		
		if (playing) {
			ctime += seconds;
			if (ctime > duration) {
				if (loop) {
					ctime %= duration;
				} else {
					ctime = frames[0];
				}
			}
		}
		
		int frame = getFrameNumber();
		
		grid.drawFrame(frameGraphics, frame);
	}
}
